package com.beiing.tianshuai.tianshuai.message.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.GroupAddMembersAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.ContactsBean;
import com.beiing.tianshuai.tianshuai.entity.GroupDetailsBean;
import com.beiing.tianshuai.tianshuai.entity.MyFriendListBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.message.presenter.GroupAddMembersPresenter;
import com.beiing.tianshuai.tianshuai.message.view.GroupAddMembersViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.PinYinUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.SideLitterBarView;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.team.TeamService;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

public class GroupAddMembersActivity extends BaseActivity implements GroupAddMembersViewImpl {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_btn_publish)
    TextView mSubmit;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTitle;
    @BindView(R.id.my_friends_list)
    ListView listView;
    @BindView(R.id.side_navigation)
    SideLitterBarView wordsNavigation;
    @BindView(R.id.tv_center)
    TextView tvCenter;

    private static final String TAG = "GroupAddMembersActivity";
    public static final int MAX_MEMBER_NUMBER = 50;
    private Handler mHandler = new Handler();
    private List<String> mMembersChoice = new ArrayList<>();
    private List<String> mChoiceName = new ArrayList<>();
    private Context mContext;
    private List<ContactsBean> mContactList;
    private GroupAddMembersAdapter mAdapter;
    private GroupAddMembersPresenter mPresenter;
    private List<GroupDetailsBean.DataBean.NumberBean.UserBean> mMembers;
    private String mGroupId;
    private String mGId;
    private String isOwner;

    /**
     * 已选择人数
     */
    private int mChoiceCount = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group_add_members;
    }

    @Override
    protected void init() {
        ButterKnife.bind(this);
        mContext = this;
        initData();
        initToolbar();
        initAdapter();
        initListener();
        initPresenter();
    }

    private void initToolbar() {
        mSubmit.setVisibility(View.VISIBLE);
        mToolbarBack.setVisibility(View.VISIBLE);
        mToolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mToolbarTitle.setText(
                MessageFormat.format("添加群成员（{0}/{1}）",
                        mChoiceCount, MAX_MEMBER_NUMBER)
        );

        mSubmit.setText("完成");
    }

    private void initData() {
        Intent intent = getIntent();
        mMembers = ((List<GroupDetailsBean.DataBean.NumberBean.UserBean>)
                intent.getSerializableExtra("members"));
        mGId = intent.getStringExtra("gId");
        mGroupId = intent.getStringExtra("easeGId");
        isOwner = intent.getStringExtra("isOwner");
        LogUtils.i(mMembers.toString(), TAG);
    }

    private void initAdapter() {
        mContactList = new ArrayList<>();
        mAdapter = new GroupAddMembersAdapter(this, mContactList, mMembers);
        listView.setAdapter(mAdapter);
    }

    private void initListener() {
        // 完成
        mSubmit.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                LogUtils.i(mMembersChoice.toString(), TAG);
                StringBuilder members = new StringBuilder();
                for (int i = 0; i < mMembersChoice.size(); i++) {
                    String uid = mMembersChoice.get(i);
                    if (i < mMembersChoice.size() - 1) {
                        members.append(uid).append(",");
                    } else {
                        members.append(uid);
                    }
                }
                mPresenter.getAddMembersRequestResponse(
                        mGId,
                        mGroupId,
                        UserInfoBean.getUid(mContext),
                        members.toString(),
                        isOwner
                );
            }
        });

        // 控制器点击事件
        mAdapter.setListener(new GroupAddMembersAdapter.OnItemClick() {
            @Override
            public void onItemClickListener(int position, boolean isChecked, ContactsBean bean) {
                String uid = bean.getUid();
                String name = bean.getName();
                if (isChecked) {
                    if (mChoiceCount >= MAX_MEMBER_NUMBER) {
                        bean.setChecked(false);
                        mAdapter.notifyDataSetChanged();
                        showShortText("最多选择50人");
                        return;
                    }
                    mMembersChoice.add(uid);
                    mChoiceName.add(name);
                    mChoiceCount++;
                } else {
                    mMembersChoice.remove(uid);
                    mChoiceName.remove(name);
                    mChoiceCount--;
                }

                // 设置标题
                mToolbarTitle.setText(
                        MessageFormat.format("添加群成员（{0}/{1}）",
                                mChoiceCount, MAX_MEMBER_NUMBER)
                );

            }
        });

        // 快捷导航栏
        wordsNavigation.setListener(new SideLitterBarView.onWordsChangeListener() {
            @Override
            public void wordsChange(String words) {
                if (mContactList != null) {
                    updateWord(words);
                    updateListView(words);
                }
            }
        });

        // listView设置滑动监听
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (mContactList != null && mContactList.size() > 0) {
                    wordsNavigation.setTouchIndex(mContactList.get(i).getFirstLetter());
                }
            }
        });
    }

    private void updateWord(String words) {
        tvCenter.setText(words);
        tvCenter.setVisibility(View.VISIBLE);
        mHandler.removeCallbacksAndMessages(null);
        // 500ms后消失显示
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                tvCenter.setVisibility(View.GONE);
            }
        }, 500);
    }

    private void updateListView(String words) {
        for (int i = 0; i < mContactList.size(); i++) {
            //将手指按下的字母与列表中相同字母开头的项找出
            if (words.equals(mContactList.get(i).getFirstLetter())) {
                listView.setSelection(i);
                break;
            }
        }
    }

    private void initPresenter() {
        mPresenter = new GroupAddMembersPresenter(this);
        mPresenter.getAllConstantsRequestResponse(UserInfoBean.getUid(mContext));
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在努力加载，请稍后...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(CodeBean bean) {
        if (bean.getCode() == 200) {
            NIMClient.getService(TeamService.class).addMembers(mGroupId, mMembersChoice)
                    .setCallback(new RequestCallback<List<String>>() {
                        @Override
                        public void onSuccess(List<String> strings) {
                            LogUtils.i(strings.toString(), TAG);
                        }

                        @Override
                        public void onFailed(int i) {
                            LogUtils.i(String.valueOf(i), TAG);
                        }

                        @Override
                        public void onException(Throwable throwable) {
                            LogUtils.e(throwable.getMessage(), TAG);
                        }
                    });
            finish();
        } else {
            showShortText("操作失败");
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.toString(), "Error");
    }

    @Override
    public void getAllConstantsSuccess(MyFriendListBean bean) {
        List<MyFriendListBean.DataBean.NumberBean> friends = bean.getData().getNumber();
        if (friends.size() > 0) {
            for (MyFriendListBean.DataBean.NumberBean friend : friends) {
                try {
                    String name = friend.getName();
                    String uid = friend.getUid();
                    String avatar = friend.getPhoto();
                    String unit = friend.getUnit();
                    ContactsBean contactBean = new ContactsBean();
                    contactBean.setName(name);
                    contactBean.setAvatar(avatar);
                    contactBean.setUid(uid);
                    contactBean.setUnit(unit);
                    contactBean.setFirstLetter(PinYinUtils.getPinyin(name).substring(0, 1));
                    mContactList.add(contactBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Collections.sort(mContactList, new Comparator<ContactsBean>() {
                @Override
                public int compare(ContactsBean contactBean, ContactsBean t1) {
                    return contactBean.getFirstLetter().compareTo(t1.getFirstLetter());
                }
            });
            mAdapter.notifyDataSetChanged();
        }
    }
}
